
import json
from sanic import Websocket
from uuid import UUID
from apps.base.hunter import AppError
from modules.xfyun.auth import XFYunAuth


AUTH_URL = "wss://spark-api.xf-yun.com/v3.5/chat"
# 不知道是干啥的
answer = ""
sid = ''


class ChatAuthExt(XFYunAuth):
    """
    用于扩展认知模型的参数
    https://www.xfyun.cn/doc/spark/general_url_authentication.html
    """

    def __init__(self):
        """
        AudioFile: 语音文件保存路径
        """
        super().__init__(XFYun_URL=AUTH_URL)
        self.domain = "generalv3.5"


def _gen_params(user_id: UUID, appid: str, query: str, domain: str) -> str:
    """
    通过appid和用户的提问来生成请参数
    """

    data = {
        "header": {
            "app_id": appid,
            "uid": user_id.hex,
            # "patch_id": []    #接入微调模型，对应服务发布后的resourceid
        },
        "parameter": {
            "chat": {
                "domain": domain,
                "temperature": 0.5,
                "max_tokens": 4096,
                "auditing": "default",
            }
        },
        "payload": {"message": {"text": [{"role": "user", "content": query}]}},
    }
    return json.dumps(data)


async def send_chat(ws, wsParam, userid: UUID, query: str, ):
    """
    发送数据到chat
    """
    data = _gen_params(userid, wsParam.APP_ID, query, wsParam.domain)
    await ws.send_str(data)


async def recv_chat(ws: Websocket, message: str) -> str:
    """
    接收数据到chat
    """
    data = json.loads(message)
    code = data['header']['code']
    if code != 0:
        await ws.close()
        raise AppError(10002, F"spark返回错误code:{code}")
    else:
        global sid
        sid = data["header"]["sid"]
        choices = data["payload"]["choices"]
        status = choices["status"]
        content = choices["text"][0]["content"]
        print(content,end ="")
        if status == 2:
            await ws.close()
        global answer
        answer += content
        return answer
        # print(1)



